package com.ltu.timkor6.gamesite.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.ltu.timkor6.gamesite.shared.DBGames;
import com.ltu.timkor6.gamesite.shared.DBUsers;
import com.ltu.timkor6.gamesite.shared.Result;

public class DataBaseConnection
{
	private GameSiteServiceImpl gameSite;
	
	public DataBaseConnection(GameSiteServiceImpl gameSite)
	{
		this.gameSite = gameSite;
	}
	
	@SuppressWarnings("unchecked")
	public void addResult(Result result)
	{
		PersistenceManager pm = this.gameSite.getPersistenceManager();
		try
		{
			// Insert game result
			DBGames game = new DBGames(this.gameSite.userInfo.getUserName(), result.getGameTitle());
			game.setPoints(result.getPoints());
			game.setTime(result.getTime());
			game.setTurns(result.getTurns());
			pm.makePersistent(game);
			
			
			// Update user
			pm.currentTransaction().begin();
			
			Query query = pm.newQuery(DBUsers.class, "userName == " + this.gameSite.userInfo.getUserName());
			Collection<DBUsers> collection = (Collection<DBUsers>) query.execute();
			DBUsers user = collection.iterator().next();
			
			if(user != null)
			{
				user.setPoints(user.getPoints() + result.getPoints());
				
				pm.currentTransaction().commit();
			}
		}
	    catch (Throwable t)
	    {
	    	// Rollback in case of errors
	    	pm.currentTransaction().rollback();
	    }
		finally
		{
			pm.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Result> getResult()
	{
		PersistenceManager pm = this.gameSite.getPersistenceManager();
		
		List<Result> list = new ArrayList<Result>();
		try
		{
			Query q = pm.newQuery("select from " + DBGames.class.getName() + " where userName == " + this.gameSite.userInfo.getUserName() + " order by createdDate");
			List<DBGames> db = (List<DBGames>) q.execute();
			for(DBGames info : db)
			{
				Result result = new Result();
				result.setGameTitle(info.getGameTitle());
				result.setPoints(info.getPoints());
				result.setTime(info.getTime());
				result.setTurns(info.getTurns());
				
				list.add(result);
			}
		}
		finally
		{
			pm.close();
		}
		
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<Result> getResultForAll()
	{
		PersistenceManager pm = this.gameSite.getPersistenceManager();
		
		List<Result> list = new ArrayList<Result>();
		try
		{
			Query q = pm.newQuery("select from " + DBUsers.class.getName() + " order by points");
			List<DBUsers> db = (List<DBUsers>) q.execute();
			for(DBUsers info : db)
			{
				Result result = new Result();
				result.setDate(info.getDate());
				result.setPoints(info.getPoints());
				result.setUserName(info.getUserName());
				
				list.add(result);
			}
		}
		finally
		{
			pm.close();
		}
		
		return list;
	}
}
